<template>
  <div class="app-list" v-loading="loading">
    <el-empty :image-size="200" v-if="!tableData.length" />
    <el-card class="line-item" v-for="(item, index) in tableData" :key="index">
      <div class="url" @click="handleOpenUrl(item)"> {{ item.domain }}/{{ item.hash }}</div>
      <div class="tagList">
        <el-tag :type="item.redirectMode == 0 ? 'primary' : 'success'">
          {{ item.redirectMode == 0 ? '轮询模式' : "记忆模式" }}
        </el-tag>
        <el-tag :type="item.isInterceptProxy ? 'primary' : 'success'">
          {{ item.isInterceptProxy ? "已开启过滤代理" : "未开启过滤代理" }}
        </el-tag>
        <el-tag v-if="(typeof item.countryFilterMode == 'number')">
          {{ item.countryFilterMode == 0 ? "只放行" : "只拦截" }}
          {{ getCountryName(item.country) }}
        </el-tag>
        <el-tag type="error">拦截请求次数{{ item.prohibitedCount }}</el-tag>
      </div>
      <div class="line-head">
        <div class="lf">
          <el-button type="primary" @click="handleOpenFl(item.id)">新增分流</el-button>
          <el-button type="success" @click="handleCopyUrl(item)">复制网址</el-button>
        </div>
        <div class="rg">
          <el-button type="primary" link :icon="Filter" @click="handleFilterCity(item)">限制IP归属地</el-button>
          <el-button type="primary" link :icon="Refresh" @click="handleRestLineCount(item.id)">重置</el-button>
          <el-button type="primary" link :icon="EditIcon" @click="setLine(item)">编辑</el-button>
          <el-button type="danger" link :icon="DeleteFilled" @click="deleteLine(item.id)">删除</el-button>
        </div>
      </div>
      <div class="line-tags">
        <div class="lf">
          <el-tag v-for="(v, i) in item.tags" :key="i" type="primary">{{ v }}</el-tag>
        </div>
        <div class="rg" @click="handleSetTag(item.id, item.tags)">修改标签</div>
      </div>

      <el-table :data="item.redirectTargets">
        <el-table-column type="index" label="#" />
        <el-table-column prop="target" label="网址/电话" />
        <el-table-column prop="nonRepetitiveIpRequestCount" label="不重复点击数" width="200" />
        <el-table-column label="编辑选项" width="250">
          <template #default="scope">
            <!-- {{ scope.row.isActive }} -->
            <el-switch @change="hanldeSwitchchange($event, item.id, scope.row.id)" v-model="scope.row.isActive" />
            <el-button type="primary" style="margin-left:10px" @click.prevent="editRow(scope.row, item.id)">修改</el-button>
            <el-button type="danger" @click.prevent="deleteRow(scope.row, item.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <EditLine title="修改短网址" v-model="isLine" v-if="isLine" @close="isLine = false" :lineItem="lineItem"
      @success="restListData"></EditLine>
    <EditBypass v-model="isEdit" v-if="isEdit" title="修改分流" @close="isEdit = false" :lineItem="lineItem"
      @success="restListData"></EditBypass>
    <AddBypass v-model="isAdd" v-if="isAdd" title="新增分流" @close="isAdd = false" :id="itemId" @success="restListData">
    </AddBypass>
    <EditTag v-model="isTag" v-if="isTag" title="修改标签页" @close="isTag = false" :id="itemId" :list="tagList"
      @success="restListData"></EditTag>
    <FilterCity v-model="isFilter" v-if="isFilter" title="限制ip归属地" @close="isFilter = false" :info="lineItem" :id="itemId"
      @success="restListData">
    </FilterCity>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { DeleteFilled, Edit as EditIcon, Refresh, Filter } from '@element-plus/icons-vue'
import { ref, defineExpose } from 'vue'
import { getLine, delLine, delLineDetail, getLineUrl, switchActive, switchInActive, restLineCount } from '@/server/home'
import EditBypass from './components/EditBypass.vue';
import AddBypass from './components/AddBypass.vue';
import EditTag from './components/EditTag.vue';
import FilterCity from './components/FilterCity.vue';
import EditLine from './components/EditLine.vue';
import { useStore } from "vuex"
import countryData from './country.js'
const store = useStore()
const isLine = ref(false)
const isEdit = ref(false)
const isAdd = ref(false)
const isTag = ref(false)
const isFilter = ref(false)
const tableData: any = ref([])
const lineItem = ref({})
const loading = ref(false)
const props = defineProps({
  filter: {
    type: Object,
    default: () => { }
  }
})
const hostUrl = ref(location.origin)
//获取国家名称
function getCountryName(name: string) {
  return countryData.find((x: any) => x.countryEn == name).country
}
//打开Url
const handleOpenUrl = (item: any) => {
  // window.open(hostUrl.value+'/'+hash)
  window.open('http://' + item.domain + '/' + item.hash)
}
//复制url
const handleCopyUrl = async (item: any) => {
  const url = 'http://' + item.domain + '/' + item.hash
  let inputDom = document.createElement('textarea') // js创建一个文本框
  document.body.appendChild(inputDom) //将文本框暂时创建到实例里面
  inputDom.value = url //将需要复制的内容赋值到创建的文本框中
  inputDom.select() //选中文本框中的内容
  inputDom.focus()
  document.execCommand('copy') //执行复制操作
  document.body.removeChild(inputDom)
  ElMessage.success("复制成功")
}
//新增分流
const handleOpenFl = (id: string) => {
  itemId.value = id
  isAdd.value = true
}
//修改标签
const tagList = ref([])
const itemId = ref('')
const handleSetTag = (id: string, tags: any) => {
  itemId.value = id
  tagList.value = tags
  isTag.value = true
}
//修改分流
const editRow = (item: any, id: string) => {
  lineItem.value = { ...item, redirectTargetId: item.id, id }
  isEdit.value = true
}
//删除分流
const deleteRow = (item: any, id: string) => {
  ElMessageBox.confirm(
    '分流确定要删除?',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delLineDetail(id, item.id)
      ElMessage.success("删除成功")
      getlineData()
    })

}
//修改短网址
const setLine = (item: object) => {
  lineItem.value = item
  isLine.value = true
}
//限制ip归属地
function handleFilterCity(item: any) {
  lineItem.value = {
    isInterceptProxy: item.isInterceptProxy,
    countryFilterMode: item.countryFilterMode,
    country: item.country
  }
  itemId.value = item.id
  isFilter.value = true
}
//重置
const handleRestLineCount = async (id: string) => {
  ElMessageBox.confirm(
    '确定要重置?',
    '确认重置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await restLineCount(id)
        ElMessage.success("重置成功")
        getlineData()
      } catch (err) {
        ElMessage.success("重置失败")
      }
    })

}
//删除短网址
const deleteLine = async (id: string) => {
  ElMessageBox.confirm(
    '短网址确定要删除?',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delLine(id)
      ElMessage.success("删除成功")
      getlineData()
    })
}
//重置列表
const restListData = () => {
  isEdit.value = false;
  isTag.value = false;
  isAdd.value = false;
  isLine.value = false;
  isFilter.value = false
  getlineData()
}
//开关分流
const hanldeSwitchchange = async (e: boolean, id: string, itemId: string) => {
  if (e) {
    await switchActive(id, itemId)
    ElMessage.success("打开成功")
  } else {
    await switchInActive(id, itemId)
    ElMessage.success("关闭成功")
  }
}
//获取列表
const getlineData = async () => {
  loading.value = true
  const params = {
    Filter: props.filter.search,
    Sorting: `${props.filter.sort} desc`,
    SkipCount: props.filter.page > 1 ? (props.filter.page - 1) * props.filter.pages : 0,
    MaxResultCount: props.filter.pages
  }
  const data = await getLine(params)
  tableData.value = data.items
  loading.value = false
  store.commit("changeTotal", data.totalCount)
}
getlineData()
defineExpose({ restListData })
</script>
<style lang="scss" scoped>
.app-list {
  // height: 64vh;
  // margin-bottom: 10px;
  overflow: auto;

  .line-item {
    margin: 2rem 0;

    .url {
      display: inline-block;
      margin-bottom: 20px;
      text-decoration: underline;
      cursor: pointer;
      font-weight: bold;
    }

    .tagList {
      display: flex;
      margin-bottom: 20px;

      .el-tag+.el-tag {
        margin-left: 5px;
      }
    }

    .line-head {
      display: flex;
      justify-content: space-between;
      margin-bottom: 1rem;

      .rg {
        display: flex;
        align-items: center;

        .type1 {
          color: var(--el-color-primary);
          font-weight: bold;
        }

        .type2 {
          color: var(--el-color-success);
          font-weight: bold;
        }

        .el-icon {
          cursor: pointer;
          margin-left: 20px;
        }

        // .el-icon:nth-child(1){
        //   color: var(--el-color-success);
        // }
        .el-icon:nth-child(2) {
          color: var(--el-color-primary);
        }

        .el-icon:nth-child(3) {
          color: var(--el-color-primary);
        }

        .el-icon:last-child {
          color: red;
        }
      }
    }

    .line-tags {
      display: flex;
      justify-content: space-between;

      .lf {
        .el-tag {
          margin-right: 10px;
        }
      }

      .rg {
        color: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }
}
</style>